package app.controller.city;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import app.entity.Pager;
import app.entity.UserSession;
import app.entity.Worker;
import app.entity.WorksInfo;
import app.service.UnitService;
import app.utils.Common;
import app.utils.DataResponse;
import siotwx.entity.User;
@Controller
public class UnitController {
	@Autowired
	@Qualifier("UnitService")
	private UnitService unitService;
	
	@RequestMapping(value="/unit/{orgid}/users",method=RequestMethod.GET)
	public void unitUsres(@PathVariable("orgid") Integer orgid,Integer pageNum,HttpServletResponse response){
		pageNum=pageNum==null?1:pageNum;
		Integer userCount = unitService.getUserCount(orgid);
		Pager pager=new Pager(userCount, pageNum,8);
		List<User> users = unitService.getUsers(orgid,pager);
		WorksInfo worksInfo=new WorksInfo();
		worksInfo.setPage(pager.getPagenumber()+"");
		worksInfo.setTotal(userCount+"");
		List<Worker> workers=new ArrayList<>();
		int num=1;
		for(User user:users){
			workers.add(new Worker((pageNum-1)*8+num++, user.getRealName(), user.getPhoneNumber(), user.getId(), orgid));
		}
		worksInfo.setWorkers(workers);
		DataResponse.jsonResponse(response, worksInfo);
	}
	
	@RequestMapping(value="/unit/deluser/{id}",method=RequestMethod.POST)
	public void delUser(@PathVariable("id") Integer userid,HttpServletResponse response){
		int delUser = unitService.delUser(userid);
		DataResponse.jsonResponse(response, delUser);
	}
	
	@RequestMapping(value="/unit/addunit",method=RequestMethod.POST)
	public String addCompany(String name,String cname,String tel,String address,String email,HttpSession session){
		UserSession user = (UserSession) session.getAttribute(Common.sessionUser);
		Integer region=user==null?1:user.getRegionId();
		unitService.addUnit(name, cname, tel, address, email, region);
		
		return "redirect:../2/unitandstaff";
	}
	
	@RequestMapping(value="/unit/del/{id}",method=RequestMethod.POST)
	public void delUnit(@PathVariable("id") Integer id,HttpServletResponse response){
		int res=0;
		res = unitService.delUnit(id);
		DataResponse.jsonResponse(response, res);
	}
	
	//该方法用于同意工人进入单位
	@RequestMapping("/unit/agreeTo/{userId}")
	public void agreeTo(HttpServletResponse response,@PathVariable("userId") Integer userId){
		Integer addTo = unitService.addTo(userId);
		DataResponse.jsonResponse(response, addTo);
	}
}
